package org.bim.view.drag.design.config;

import org.bim.view.drag.design.constant.CommonConstant;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.mitre.dsmiley.httpproxy.URITemplateProxyServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;

@Configuration
public class OssProxyConfig {
    private static final String TARGET_URI="targetUri";
    @Value("${app.upload.prefix:/oss/*}")
    private String prefix;
    /**
     * 本地：local，Minio：minio，阿里云：alioss,恒嘉 oss： hj-oss
     */
    @Value(value = "${app.upload.mode}")
    private String uploadType;
    @Resource
    private AliOssProperties aliOssProperties;
    @Resource
    private MinioProperties minioProperties;
    @Bean
    @Order(10)
    public ServletRegistrationBean<URITemplateProxyServlet> ossProxy(){
        URITemplateProxyServlet servlet = new URITemplateProxyServlet();
        ServletRegistrationBean<URITemplateProxyServlet>  registration = new ServletRegistrationBean<>(servlet,prefix);
        registration.setName("ossUrl");
        if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) {
            registration.addInitParameter(TARGET_URI, getMinioUrl());
        } else {
         String newBucket =   aliOssProperties.getBucketName();
         String endPoint = aliOssProperties.getEndpoint();
         String target = "https://" + newBucket + "." + endPoint;
         registration.addInitParameter(TARGET_URI,target);
        }
        registration.addInitParameter(ProxyServlet.P_LOG, "true");
        return registration;
    }

    private String getMinioUrl(){
        String minioUrl =minioProperties.getMinioUrl();
        if(!minioUrl.startsWith("http") &&  !minioUrl.startsWith("https")){
            minioUrl = "http://" + minioUrl;
        }
        return minioUrl;
    }
}
